package com.intxt.bbs.service;

import java.util.Date;
import java.util.UUID;

import com.intxt.bbs.model.User;
import com.jfinal.log.Logger;
import com.jfinal.plugin.activerecord.TableMapping;

public class UserService {
	private Logger log = Logger.getLogger(UserService.class);
	
	/**
	 * 注册一个用户
	 * @return 保存成功返回User , 否则返回null
	 */
	public User reg(String username, String password, String email,String ip){
		User u = new User();
    	UUID uuid = UUID.randomUUID();   
		u.set("id", uuid.toString());
		u.set("username", username);
		u.set("password", password);
		u.set("email", email);
		u.set("reg_date",new Date());
		u.set("last_login_datetime",new Date());
		u.set("last_login_ip",ip);
		if(u.save()){
			return u;
		}
		return null;
	}
	
	/**
	 * 登陆 , 如果成功返回User,否者返回null
	 * @param username
	 * @param password
	 * @return
	 */
	public User login(String username,String password){
		String sql = "select * from "+TableMapping.me().getTable(User.class).getName()+" where username ='"+username+"'";
		log.debug("登陆的sql:"+sql);
		User u = User.DAO.findFirst(sql);
		if(password.equals(u.getStr("password"))){
			return u;
		}else{
			return null;
		}
				
	}
	
	/**
	 * 通过ID获取User
	 * @param id
	 * @return
	 */
	public User getUserById(String id){
		return User.DAO.findById(id);
	}
	
	public boolean updateUser(User u){
		return u.update();
	}
	
}
